<template>
  <div>
    <HeaderIndex title="地址编辑" :showTwo="false" />
    <van-address-edit
      :area-list="areaList"
      show-delete
      @delete="onDelete"
      :address-info="Info"
      :search-result="searchResult"
      @save="onSave"
      show-postal
      show-set-default
      show-search-result
    />
  </div>
</template>

<script>
import areaList from '@/assets/js/areaList.js';
export default {
  data() {
    return {
      areaList,
      searchResult: [
        {
          name: '黄龙万科中心',
          address: '杭州市西湖区',
        },
      ],
      Info: {},
    };
  },
  created() {
    if (this.$route.query.info) {
      this.Info = JSON.parse(this.$route.query.info);
    }
  },
  methods: {
    onSave(val) {
      let arr = [];
      if (this.$route.query.info) {
        arr = JSON.parse(localStorage.getItem('addressList'));
        arr = arr.map(element => {
          if (element.id == JSON.parse(this.$route.query.info).id) {
            element = val;
            element.id = JSON.parse(this.$route.query.info).id;
          }
          return element;
        });
      } else {
        let a = 0;
        if (localStorage.getItem('addressList')) {
          arr = JSON.parse(localStorage.getItem('addressList'));
        }
        arr.push(val);
        arr.forEach(element => {
          element.id = a++;
        });
      }
      localStorage.setItem('addressList', JSON.stringify(arr));
      this.$router.push('/storeAdressList');
    },
    onDelete(val) {
      if (localStorage.getItem('addressList')) {
        let arr = JSON.parse(localStorage.getItem('addressList'));
        let a = arr.findIndex(ele => ele.id == val.id);
        arr.splice(a, 1);
        if (arr.length) {
          //有
          localStorage.setItem('addressList', JSON.stringify(arr));
        } else {
          localStorage.removeItem('addressList');
          localStorage.removeItem('currentIndexAdress');
        }
        this.$router.push('/storeAdressList');
      } else {
        this.$router.push('/storeSubmit');
      }
    },
  },
};
</script>

<style scoped></style>
